import re

from django.contrib.auth.backends import ModelBackend

#继承这个类然后重写这个类
from apps.users.models import User




#抽取的思想，就是给一个用户名，然后返回个user对象
def get_user_by_username(username):
    try:
        if re.match(r'^1[3-9]\d{9}', username):

            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    return user




class UsernameMobileModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # try:
        #     if re.match(r'^1[3-9]\d{9}',username):
        #
        #         user = User.objects.get(mobile=username)
        #     else:
        #         user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     return None
        user = get_user_by_username(username)
        if user is not None and user.check_password(password):
            return user

#定义生成邮箱验证链接方法
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

def generate_verify_email_url(user):
    """
    生成邮箱验证链接
    :param user: 当前登录用户
    :return: verify_url
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    data = {'user_id': user.id, 'email': user.email}
    token = serializer.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url


#在users.utils.py中添加生成认证的url方法
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from django.conf import settings


def check_verify_email_token(token):
    """
    验证token并提取user
    :param token: 用户信息签名后的结果
    :return: user, None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user



